<template>
	<view class="register-container">
		<view class="register-header">
			<text class="register-title">注册新用户</text>
		</view>
		
		<view class="register-form">
			<!-- 用户名输入框 -->
			<view class="input-group">
				<view class="input-label">
					<text>用户名</text>
				</view>
				<input class="input-field" type="text" placeholder="请输入用户名" placeholder-class="placeholder" v-model="username" />
			</view>
			
			<!-- 密码输入框 -->
			<view class="input-group">
				<view class="input-label">
					<text>密码</text>
				</view>
				<input class="input-field" type="text" :password="!showPassword" placeholder="请输入密码" placeholder-class="placeholder" v-model="password" />
				<view class="password-icon" @click="togglePasswordVisibility">
					<text class="iconfont">{{ showPassword ? '👁️' : '👁️‍🗨️' }}</text>
				</view>
			</view>
			
			<!-- 密码强度提示 -->
			<view class="password-tip" v-if="password">
				<view class="strength-bar">
					<view class="strength-item" :class="{ active: passwordStrength >= 1 }"></view>
					<view class="strength-item" :class="{ active: passwordStrength >= 2 }"></view>
					<view class="strength-item" :class="{ active: passwordStrength >= 3 }"></view>
					<view class="strength-item" :class="{ active: passwordStrength >= 4 }"></view>
				</view>
				<text class="strength-text">
					{{ passwordStrength < 2 ? '弱' : passwordStrength < 4 ? '中' : '强' }}
				</text>
			</view>
			<view class="password-errors" v-if="passwordErrors.length > 0">
				<text>{{ passwordErrors.join('，') }}</text>
			</view>
			
			<!-- 邮箱输入框 -->
			<view class="input-group">
				<view class="input-label">
					<text>邮箱</text>
				</view>
				<input class="input-field" type="text" placeholder="请输入邮箱" placeholder-class="placeholder" v-model="email" @blur="validateEmail" />
			</view>
			
			<!-- 邮箱错误提示 -->
			<view class="email-tip" v-if="emailError">
				<text>请输入正确的邮箱格式</text>
			</view>
			
			<!-- 手机号输入框 -->
			<view class="input-group">
				<view class="country-code">
					<text>+86</text>
					<text class="arrow-down">▼</text>
				</view>
				<input class="input-field" type="number" placeholder="请输入您的手机号" placeholder-class="placeholder" v-model="phone" @blur="validatePhone" />
			</view>
			
			<!-- 手机号错误提示 -->
			<view class="phone-tip" v-if="phoneError">
				<text>请输入正确的手机号格式</text>
			</view>
			
			
			<!-- 注册按钮 -->
			<view class="register-button" @click="register">
				<text>注册</text>
			</view>
		</view>
	</view>
</template>

<script>
import Validator, { VALIDATION_RULES } from '@/utils/validator.js'
import { userAPI } from '@/utils/api.js'
import { showSuccess, showError } from '@/utils/toast.js'

export default {
	data() {
		return {
			username: '',
			password: '',
			email: '',
			phone: '',
			showPassword: false,
			emailError: false,
			phoneError: false,
			passwordStrength: 0,
			passwordErrors: []
		}
	},
	methods: {
		togglePasswordVisibility() {
			this.showPassword = !this.showPassword;
		},
		
		validateEmail() {
			// 邮箱格式验证
			this.emailError = !Validator.isValidEmail(this.email) && this.email !== '';
		},
		
		validatePhone() {
			// 手机号格式验证
			this.phoneError = !Validator.isValidPhone(this.phone) && this.phone !== '';
		},
		
		/**
		 * 验证密码强度
		 */
		validatePasswordStrength() {
			if (!this.password) {
				this.passwordStrength = 0;
				this.passwordErrors = [];
				return;
			}
			
			const result = Validator.validatePassword(this.password);
			this.passwordStrength = result.strength;
			this.passwordErrors = result.errors;
		},
		
		
		/**
		 * 表单验证
		 */
		validateForm() {
			const formData = {
				username: this.username,
				password: this.password,
				email: this.email,
				phone: this.phone
			};
			
			const result = Validator.validateForm(formData, VALIDATION_RULES.REGISTER);
			
			if (!result.isValid) {
				showError(result.firstError);
				return false;
			}
			
			return true;
		},
		
		/**
		 * 注册处理
		 */
		async register() {
			// 表单验证
			if (!this.validateForm()) {
				return;
			}
			
			try {
				// 准备注册数据（匹配后端可能的注册接口格式）
				const registerData = {
					username: this.username,
					password: this.password,
					email: this.email,
					mobile: this.phone // 使用mobile字段匹配UserInfoDto
				};
				
				// 调用注册接口 - 直接调用后端API
				const result = await userAPI.register(registerData);
				
				console.log('注册响应:', result);
				
				if (result.code === 200) {
					showSuccess('注册成功');
					
					// 保存用户令牌和信息
					if (result.data && result.data.token) {
						uni.setStorageSync('asurada_user_token', result.data.token);
						
						if (result.data.user) {
							uni.setStorageSync('asurada_user_info', JSON.stringify(result.data.user));
						}
					}
					
					// 注册成功后跳转到登录页面
					setTimeout(() => {
						uni.navigateBack();
					}, 1500);
				} else {
					// 处理其他状态码
					const errorMsg = result.message || '注册失败，请稍后再试';
					showError(errorMsg);
				}
				
			} catch (error) {
				console.error('注册失败:', error);
				// 显示具体的错误信息
				const errorMsg = error.message || '注册失败';
				showError(errorMsg);
			}
		}
	},
	
	watch: {
		// 监听密码变化，实时验证强度
		password() {
			this.validatePasswordStrength();
		},
		
		// 监听邮箱变化
		email() {
			if (this.email) {
				this.validateEmail();
			} else {
				this.emailError = false;
			}
		},
		
		// 监听手机号变化
		phone() {
			if (this.phone) {
				this.validatePhone();
			} else {
				this.phoneError = false;
			}
		}
	}
}
</script>

<style>
.register-container {
	display: flex;
	flex-direction: column;
	min-height: 100vh;
	background-color: #1e2433;
	padding: 0 30rpx;
}

.register-header {
	margin-top: 150rpx;
	margin-bottom: 80rpx;
}

.register-title {
	font-size: 48rpx;
	color: #ffffff;
	font-weight: bold;
}

.input-group {
	display: flex;
	align-items: center;
	background-color: #2a304d;
	border-radius: 50rpx;
	padding: 20rpx 30rpx;
	margin-bottom: 30rpx;
	height: 90rpx;
}

.country-code {
	display: flex;
	align-items: center;
	color: #ffffff;
	margin-right: 20rpx;
	font-size: 32rpx;
}

.arrow-down {
	font-size: 20rpx;
	margin-left: 10rpx;
	color: #8a8a9a;
}

.input-label {
	color: #ffffff;
	font-size: 32rpx;
	margin-right: 20rpx;
	width: 120rpx;
}

.input-field {
	flex: 1;
	color: #ffffff;
	font-size: 32rpx;
}

.placeholder {
	color: #8a8a9a;
}

.password-icon {
	color: #8a8a9a;
	font-size: 40rpx;
}

.password-tip {
	display: flex;
	align-items: center;
	margin-top: -10rpx;
	margin-bottom: 20rpx;
	padding-left: 10rpx;
}

.strength-bar {
	display: flex;
	margin-right: 20rpx;
}

.strength-item {
	width: 40rpx;
	height: 6rpx;
	background-color: #3a4366;
	margin-right: 8rpx;
	border-radius: 3rpx;
	transition: background-color 0.3s;
}

.strength-item.active {
	background-color: #4a9eff;
}

.strength-item:last-child {
	margin-right: 0;
}

.strength-text {
	color: #4a9eff;
	font-size: 24rpx;
}

.password-errors {
	color: #ff4a4a;
	font-size: 24rpx;
	margin-top: -10rpx;
	margin-bottom: 20rpx;
	padding-left: 10rpx;
}

.email-tip, .phone-tip {
	color: #ff4a4a;
	font-size: 24rpx;
	margin-top: -10rpx;
	margin-bottom: 20rpx;
	padding-left: 10rpx;
}


.register-button {
	display: flex;
	justify-content: center;
	align-items: center;
	background-color: #4e5eff;
	border-radius: 50rpx;
	height: 90rpx;
	margin-top: 60rpx;
	color: #ffffff;
	font-size: 32rpx;
}
</style>